<?php

namespace App\Http\Controllers;

use App\B2BProject\Custom\Business\GoodsCategory;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class GoodsCategoryGetterController extends Controller
{
    /**
     * 获取分类信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getIndex()
    {
        $data    = [];
        $parents = GoodsCategory::getGlobalCategory();
        foreach ($parents as $parent) {
            $item = ['categTitle' => $parent->name];
            foreach ($parent->children as $child) {
                $item['categDetail'][] = ['txt' => $child->name, 'code' => $child->id];
            }
            $data['data'][] = $item;
        }
        return response()->json($data);
    }

    public function postIndex(Request $request)
    {
        $data = [];
        // TODO 可能需要验证表单提交上来的 id 是否正确
        if ($request->has('id')) {
            $id         = $request->input('id');
            $categories = GoodsCategory::GlobalCategory()->whereId($id)->first()->children;
        } else {
            $categories = GoodsCategory::getGlobalCategory();
        }

        foreach ($categories as $category) {
            $data[] = [
                'text' => $category->name,
                'code' => $category->id
            ];
        }

        return response()->json(['data' => $data]);
    }


    /**
     *  获取一级分类
     * @return \Illuminate\Http\JsonResponse
     */
    static public function getFirstCategory()
    {
        $parents = GoodsCategory::getGlobalCategory();
        $data    = [];
        foreach ($parents as $parent) {
            $data['data'][] = ['code' => $parent->id, 'text' => $parent->name];
        }
        return response()->json($data);
    }

    /**
     * 大后台页面的商品详情页面
     * @return \Illuminate\Http\JsonResponse
     */
    static public function getSpecial()
    {
        $parents = GoodsCategory::getGlobalCategory();
        $data    = [];
        foreach ($parents as $parent) {
            $data[] = ["code" => $parent->id, "text" => $parent->name];
        }
        return json_encode($data);
    }


    /**
     * 获取二级分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    static public function postCategory(Request $request)
    {
        $data = [];
        foreach (GoodsCategory::where('id', $request->input('code'))->where('parent_id',
            0)->firstOrFail()->children as $category) {
            $data['data'][] = ['code' => $category->id, 'text' => $category->name];
        }
        return response()->json($data);
    }

}
